package com.tfswx.ruleengine.compute.gzjy.felfunc;

import com.greenpineyu.fel.context.FelContext;
import com.tfswx.ruleengine.compute.gzjy.BaseFn;
import com.tfswx.ruleengine.compute.util.DateUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AddMonth extends BaseFn {

    private static final Pattern DATE_PATTERN = Pattern.compile("(\\d{4}-\\d{1,2}-\\d{1,2})");
    private static final Pattern DATE_CHINESE_PATTERN = Pattern.compile("(\\d{4}年\\d{1,2}月\\d{1,2}日)");

    @Override
    public Object call(Object[] arguments, FelContext context) {
        String dateStr = String.valueOf(arguments[0]);
        int num = Integer.parseInt(String.valueOf(arguments[1]));
        if (StringUtils.isBlank(dateStr)) {
            return null;
        } else {
            Matcher matcher = DATE_PATTERN.matcher(dateStr);
            Matcher matcher1 = DATE_CHINESE_PATTERN.matcher(dateStr);
            if (matcher.find()) {
                return addm(matcher.group(1), num);
            }
            if (matcher1.find()) {
                return addm(matcher1.group(1), num);
            }
            return "";
        }
    }

    private String addm(String dateStr, int num) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(DateUtil.parse(dateStr + " 00:00:00"));
        calendar.add(Calendar.MONTH, num);
        return DateUtil.format(calendar.getTime());
    }


    @Override
    public String getZwmc() {
        return "增加月份";
    }

    @Override
    public boolean isExport() {
        return true;
    }

    @Override
    public List<Param> getParams() {
        List<Param> params = new ArrayList<>();
        params.add(new Param("dateStr"));
        params.add(new Param("月份", "整数"));
        return params;
    }

    @Override
    public String getName() {
        return "addMonth";
    }
}
